package com.newsnetwork.user.controller;

import com.newsnetwork.api.BaseController;
import com.newsnetwork.api.controller.user.UserControllerApi;
import com.newsnetwork.grace.result.CommonJSONResult;
import com.newsnetwork.grace.result.ResponseStatusEnum;
import com.newsnetwork.pojo.AppUser;
import com.newsnetwork.pojo.bo.UpdateUserInfoBO;
import com.newsnetwork.pojo.vo.AppUserVO;
import com.newsnetwork.pojo.vo.UserAccountInfoVO;
import com.newsnetwork.user.service.MyFansService;
import com.newsnetwork.user.service.UserService;
import com.newsnetwork.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DingNing, HuangDekai
 * @date 2022/11/15 17:37
 * @Description: 用户信息相关
 */
@RestController
public class UserController extends BaseController implements UserControllerApi {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private MyFansService myFansService;

    @Override
    public CommonJSONResult getUserInfo(String userId) {
        // 1.判断参数不能为空
        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }
        // 2.根据userId查询用户信息
        AppUser user = getUser(userId);
        // 3.返回用户信息
        // 3.1 创建user VO,防止返回前端，多余信息泄漏
        AppUserVO appUserVO = new AppUserVO();
        BeanUtils.copyProperties(user, appUserVO);

        // 查询redis中用户的 关注数和粉丝数
        Integer fansNum = getCountsFromRedis(REDIS_WRITER_FANS_COUNTS + ":" + userId);
        if (fansNum == null) {
            fansNum = myFansService.queryFansCounts(user.getId());
            redisOperator.set(REDIS_WRITER_FANS_COUNTS + ":" + userId, String.valueOf(fansNum), 60);
        }
        appUserVO.setMyFansCounts(fansNum);

        Integer followNum = getCountsFromRedis(REDIS_MY_FOLLOW_COUNTS + ":" + userId);
        if (followNum == null) {
            followNum = myFansService.queryFollowCounts(user.getId());
            redisOperator.set(REDIS_MY_FOLLOW_COUNTS + ":" + userId, String.valueOf(followNum), 60);
        }
        appUserVO.setMyFollowCounts(followNum);

        return CommonJSONResult.ok(appUserVO);
    }
        // 提取到baseController
//    private Integer getCountsFromRedis(String key) {
//        String countsStr = redisOperator.get(key);
//        if (StringUtils.isBlank(countsStr)) {
//            return null;
//        }
//        return Integer.valueOf(countsStr);
//    }

    @Override
    public CommonJSONResult getAccountInfo(String userId) {
        // 1.判断参数不能为空
        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }
        // 2.根据userId查询用户信息
        AppUser user = getUser(userId);
        // 3.返回用户信息
        // 3.1 创建user VO,防止返回前端，多余信息泄漏
        UserAccountInfoVO userAccountInfoVO = new UserAccountInfoVO();
        BeanUtils.copyProperties(user, userAccountInfoVO);

        return CommonJSONResult.ok(userAccountInfoVO);
    }

    @Override
    public CommonJSONResult updateUserInfo(
            @Valid UpdateUserInfoBO updateUserInfoBO) {

        // 1. 校验BO 已经由 news-network-dev-common 的 com.newsnetwork.exception.GraceExceptionHandler 统一处理
//        if (result.hasErrors()) {
//            Map<String, String> map = getErrors(result);
//            return CommonJSONResult.errorMap(map);
//        }

        // 2. 执行更新操作
        userService.updateUserInfo(updateUserInfoBO);
        return CommonJSONResult.ok();
    }

    /**
     * 抽取共用方法，并后续扩展
     * @param userId 用户Id
     * @return
     */
    private AppUser getUser(String userId) {
        // 查询判断redis中是否包含用户信息，如果包含，则查询后直接返回，就不去查询数据库了
        String userJson = redisOperator.get(REDIS_USER_INFO + ":" + userId);
        AppUser user = null;
        if (StringUtils.isNotBlank(userJson)) {
            user = JsonUtils.jsonToPojo(userJson, AppUser.class);
        } else {
            user = userService.getUser(userId);
            // 由于用户信息不怎么会变动，对于一些千万级别的网站来说，这类信息不会直接去查询数据库
            // 那么完全可以依靠redis，直接把查询后的数据存入到redis中
            redisOperator.set(REDIS_USER_INFO + ":" + userId, JsonUtils.objectToJson(user));
        }
        return user;
    }

    @Value("${server.port}")
    private String myPort;

    @Override
    public CommonJSONResult queryByIds(String userIds) {
        System.out.println(myPort);

        if (StringUtils.isBlank(userIds)){
            return CommonJSONResult.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
        }

        List<AppUserVO> publisherList = new ArrayList<>();
        List<String> userIdList = JsonUtils.jsonToList(userIds, String.class);
        userIdList.stream().forEach(userId->{
            // 获得用户基本信息
            AppUserVO userVO = getBasicUserInfo(userId);
            // 添加到 publisherList 中
            publisherList.add(userVO);
        });

        return CommonJSONResult.ok(publisherList);
    }

    private AppUserVO getBasicUserInfo(String userId) {
        // 根据 userId 查询用户信息
        AppUser user = getUser(userId);
        // 返回用户信息
        AppUserVO appUserVO = new AppUserVO();
        BeanUtils.copyProperties(user, appUserVO);

        return appUserVO;
    }
}
